import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/beans/bussdetail_bean.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';

import '../apis.dart';
import '../const.dart';

final key = GlobalKey<_PageState>();
var isvalid = '';
var inscode = '';

class DetailPage extends StatefulWidget {
  final inscode;

  const DetailPage({Key key, this.inscode}) : super(key: key);

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  var loadingDialog;
  var titles1 = const [
    '行政区域',
    '培训机构编号',
    '驾培机构名称',
    '经营许可编号',
    '联系人',
    '联系电话',
    '经营许可日期',
    '法人代表',
    '培训机构简称',
    '营业执照注册号',
    '统一社会信息代码',
    '邮政编码',
    '经营范围',
    '经营状态',
    '创建时间',
    '更新时间',
    '培训机构地址',
  ];

  var titles2 = const [
    '分类等级',
    '教练车总数',
    '教练员总数',
    '考核员数',
    '教室总面积(平方米)',
    '安全管理人数',
    '理论教室面积(平方米)',
    '教练场总面积(平方米)',
  ];

  var content1 = List();
  var content2 = List();

  Page _page1, _page2;
  GlobalKey _tabBarKey = new GlobalKey();

  List<Widget> _sliverBuilder(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        backgroundColor: Color(0xff23AFDC),
        title: Text('信息详情'),
        centerTitle: true,
        //标题居中
        // expandedHeight: 200.0,  //展开高度200
        floating: false,
        //不随着滑动隐藏标题
        pinned: false, //固定在顶部
      )
    ];
  }

  _getSize() {
    RenderObject renderObject = _tabBarKey.currentContext.findRenderObject();
    print(
        "semanticBounds:${renderObject.semanticBounds.size} paintBounds:${renderObject.paintBounds.size} size:${_tabBarKey.currentContext.size}");
    return _tabBarKey.currentContext.size.height;
  }

  /*_showDialog() {
    loadingDialog = LoadingDialog(
      text: '加载中...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }*/

  _getByInscode() {
    Map data = Map<String, dynamic>();
    data["inscode"] = widget.inscode;
    MyDio.getInstance().get('/api/bussSch/getByInscode', (data) {
      print(data);
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      BussdetailBean bussdetailBean = BussdetailBean.fromJson(data);
      content1.add(bussdetailBean.districtName.toString());
      content1.add(bussdetailBean.inscode.toString());
      content1.add(bussdetailBean.name.toString());
      content1.add(bussdetailBean.licnum.toString());
      content1.add(bussdetailBean.contact.toString());
      content1.add(bussdetailBean.phone.toString());
      content1.add(bussdetailBean.licetime.toString());
      content1.add(bussdetailBean.legal.toString());
      content1.add(bussdetailBean.shortname.toString());
      content1.add(bussdetailBean.business.toString());
      content1.add(bussdetailBean.creditcode.toString());
      content1.add(bussdetailBean.postcode.toString());
      content1.add(bussdetailBean.busiscope.toString());
      content1.add('经营');
      content1.add(bussdetailBean.createtime.toString());
      content1.add(bussdetailBean.updatetime.toString());
      content1.add(bussdetailBean.address.toString());
      content2.add('${bussdetailBean.level.toString()}级');
      content2.add(bussdetailBean.tracarnum.toString());
      content2.add(bussdetailBean.coachnumber.toString());
      content2.add(bussdetailBean.grasupvnum.toString());
      content2.add(bussdetailBean.classroom.toString());
      content2.add(bussdetailBean.safmngnum.toString());
      content2.add(bussdetailBean.thclassroom.toString());
      content2.add(bussdetailBean.praticefield.toString());
      isvalid = bussdetailBean.isvalid;
      if (isvalid == '1') {
        isvalid = '解除备案';
      } else if (isvalid == '2') {
        isvalid = '审核';
      }
      inscode = bussdetailBean.inscode;
      setState(() {
        key.currentState._setMystste();
      });
    }, params: data);
  }

  _setPages() {
    List<Widget> tabs = [
      renderTab(Text('企业基本信息')),
      renderTab(Text("企业经营信息")),
    ];
    _page1 = Page(key: key, titles: titles1, content: content1);
    _page2 = Page(titles: titles2, content: content2);
    return Expanded(
      key: _tabBarKey,
      child: TabBarWidget(
        initPage: 0,
        hostTitle: '111',
        tabItems: tabs,
        tabViews: [_page1, _page2],
        indicatorColor: Color(0xff23AFDC),
      ),
    );
  }

  _setButton(String string) {
    if (string == '0' || string == '4') {
      return Container();
    } else {
      return Container(
        height: 40,
        width: MediaQuery.of(context).size.width,
        child: FlatButton(
          color: Color(0xff23AFDC),
          onPressed: () async {
            if (isvalid == '审核') {
//              _auditOfPandingAction();
            } else if (isvalid == '解除备案') {
//              _removeRecordAction();
            }
          },
          child: Text(
            isvalid,
            style: TextStyle(fontSize: 16, color: Colors.white),
          ),
        ),
      );
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getByInscode();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: NestedScrollView(
            headerSliverBuilder: _sliverBuilder,
            body: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    content1.length == 0 ? '' : content1[2],
                    style: TextStyle(
                        fontSize: 16.0, color: const Color(0xff333333)),
                  ),
                  Row(
                    children: <Widget>[
                      Image.asset(
                        'images/icon_dshyz.png',
                        height: 100,
                        width: 100,
                        fit: BoxFit.fill,
                      ),
                      Image.asset(
                        'images/icon_jcbayz.png',
                        height: 100,
                        width: 100,
                        fit: BoxFit.fill,
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  _setPages(),
                  _setButton(isvalid),
                ],
              ),
            )));
  }

  renderTab(text) {
    //返回一个标签
    return Tab(
        child: Container(
      //设置paddingTop为6
      padding: EdgeInsets.only(top: 6),
      //一个列控件
      child: Column(
        //竖直方向居中
        mainAxisAlignment: MainAxisAlignment.center,
        //水平方向居中
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[text],
      ),
    ));
  }
}

class TabBarWidget extends StatefulWidget {
  final String hostTitle;
  final List<Widget> tabItems;
  final List<Widget> tabViews;
  final Color backgroundColor;
  final Color indicatorColor;
  final int initPage;
  final ValueChanged<int> onPageChanged;

  TabBarWidget(
      {Key key,
      this.hostTitle,
      this.tabItems,
      this.tabViews,
      this.backgroundColor,
      this.indicatorColor,
      this.initPage,
      this.onPageChanged})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TabBarState(
        this.tabViews, this.indicatorColor, this.initPage, this.onPageChanged);
  }
}

class _TabBarState extends State<TabBarWidget>
    with SingleTickerProviderStateMixin {
  final int _initPage;
  final List<Widget> _tabViews;
  final Color _indicatorColor;
  final ValueChanged<int> _onPageChanged;

  _TabBarState(
      this._tabViews, this._indicatorColor, this._initPage, this._onPageChanged)
      : super();
  TabController _tabController;
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
        initialIndex: _initPage, length: widget.tabItems.length, vsync: this);
    _pageController = PageController(initialPage: _initPage, keepPage: true);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TabBar(
          tabs: widget.tabItems,
          controller: _tabController,
          indicatorColor: _indicatorColor,
          indicatorSize: TabBarIndicatorSize.label,
          labelColor: Color(0xff23AFDC),
          unselectedLabelColor: Color(0xff999999),
          onTap: (index) {
            _pageController.jumpToPage(index);
          },
        ),
        Expanded(
          child: PageView(
            controller: _pageController,
            children: _tabViews,
            onPageChanged: (index) {
              _tabController.animateTo(index);
              _onPageChanged?.call(index);
            },
          ),
        ),
//       _setButton(isvalid),
      ],
    );
  }

  _setButton(String string) {
    if (string == '0' || string == '4') {
      return Container();
    } else {
      return Container(
        height: 40,
        width: MediaQuery.of(context).size.width,
        child: FlatButton(
          color: Color(0xff23AFDC),
          onPressed: () async {
            if (isvalid == '审核') {
              _auditOfPandingAction();
            } else if (isvalid == '解除备案') {
              _removeRecordAction();
            }
          },
          child: Text(
            isvalid,
            style: TextStyle(fontSize: 16, color: Colors.white),
          ),
        ),
      );
    }
  }

  _removeRecordAction() {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return new CupertinoAlertDialog(
            title: new Text(
              "提示",
            ),
            content: new Text("是否解除备案"),
            actions: <Widget>[
              new Container(
                decoration: BoxDecoration(
                    border: Border(
                        right: BorderSide(color: Colors.white70, width: 1.0),
                        top: BorderSide(color: Colors.white70, width: 1.0))),
                child: FlatButton(
                  child: new Text("确定"),
                  onPressed: () {
                    _postButton('0');
                    Navigator.pop(context);
                  },
                ),
              ),
              new Container(
                decoration: BoxDecoration(
                    border: Border(
                        top: BorderSide(color: Colors.white70, width: 1.0))),
                child: FlatButton(
                  child: new Text("取消"),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              )
            ],
          );
        });
  }

  _auditOfPandingAction() {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return new CupertinoAlertDialog(
            title: new Text(
              "提示",
            ),
            content: new Text("确认审核"),
            actions: <Widget>[
              new Container(
                decoration: BoxDecoration(
                    border: Border(
                        right: BorderSide(color: Colors.white70, width: 1.0),
                        top: BorderSide(color: Colors.white70, width: 1.0))),
                child: FlatButton(
                  child: new Text("审核通过"),
                  onPressed: () {
                    _postButton('1');
                    Navigator.pop(context);
                  },
                ),
              ),
              new Container(
                decoration: BoxDecoration(
                    border: Border(
                        top: BorderSide(color: Colors.white70, width: 1.0))),
                child: FlatButton(
                  child: new Text("审核不通过"),
                  onPressed: () {
                    _postButton('4');
                    Navigator.pop(context);
                  },
                ),
              ),
              new Container(
                decoration: BoxDecoration(
                    border: Border(
                        top: BorderSide(color: Colors.white70, width: 1.0))),
                child: FlatButton(
                  child: new Text("取消"),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              )
            ],
          );
        });
  }

  _postButton(String string) {
    Map data = Map<String, dynamic>();
    data['inscode'] = inscode;
    data['isvalid'] = string;
    MyDio.getInstance(url: Const.BASEURL).post(Apis.bussschUpdate, (data) {
      print(data);

      if (data['code'] == 0) {}
    }, params: data);
  }
}

class Page extends StatefulWidget {
  final titles;
  final content;

  const Page({Key key, this.titles, this.content}) : super(key: key);

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  var _titles;
  var _content;

  _setMystste() {
    setState(() {});
  }

  _doWidgets(List list) {
    var widgets = List();
    for (int i = 0; i < widget.titles.length; i++) {
      widgets.add(Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            _titles[i],
            style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
          ),
          Text(
            _content.length == 0 ? '' : _content[i],
            style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
          ),
        ],
      ));
    }
    return widgets;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _titles = widget.titles;
    _content = widget.content;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10, top: 0),
      child: ListView.separated(
        shrinkWrap: true,
        itemBuilder: (context, index) => _doWidgets(_titles)[index],
        separatorBuilder: (context, index) => Divider(
          color: Color(0xffF0F0F0),
        ),
        itemCount: _doWidgets(_titles).length,
      ),
    );
  }
}
